from odoo import fields, models, api
from odoo.exceptions import UserError


class RESCity(models.Model):
    _name = "res.city"
    _inherit = ['res.city']
    _description = '市'

    @api.model
    def default_get(self, fields):
        res = super(RESCity, self).default_get(fields)
        if self._context.get('state'):
            res.update({
                'state': self._context.get('state'),
                'country_id': self._context.get('country_id'),
            })
        return res

    name = fields.Char(string='名称', required=True)
    country_id = fields.Many2one(comodel_name='res.country', string='国家', required=True)
    state_id = fields.Many2one(comodel_name='res.country.state', string='省', required=True)

    @api.constrains('name', 'country_id', 'state_id')
    def _check_info(self):
        for s in self:
            if all([s.name, s.country_id, s.state_id]):
                rcds = self.env['res.city'].search([('name', '=', s.name),
                                                    ('country_id', '=', s.country_id.id),
                                                    ('state_id', '=', s.state_id.id)])
                if len(rcds) > 1:
                    raise UserError('同国、同省中，市名不能相同')

    @api.onchange('country_id')
    def _onchange_state(self):
        if self.state_id and (self.state_id.id not in self.country_id.state_ids.ids):
            self.state_id = False
